import { Injectable } from "@nestjs/common";
import { In, Like, Repository } from "typeorm";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "@/modules/user/entities/user.entity";

export class CrudService {
    
    // constructor(
    // 	@InjectRepository(AAA)
    // 	private readonly AAARepository: Repository<AAA>
    // ) {
    // }
    
    private readonly Repository;
    
    constructor(Repository) {
        this.Repository = "";
    }
    
    async create(createDto) {
        return ResultData.ok(instanceToPlain(await this.Repository.save(createDto)));
    }
    
    async findAll(findAllDto) {
        const { page, size, username, status } = findAllDto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(status === 0 || status ? { status } : null),
            ...(username ? { username: Like(`%${username}%`) } : null)
        };
        return ResultData.rowOk(instanceToPlain(await this.Repository.findAndCount({
            order: {
                id: "DESC"
            },
            where,
            relations: {
                roles: true
            },
            skip,
            take
        })));
    }
    
    async findOne(id: number) {
        ResultData.ok(instanceToPlain(await this.Repository.findOneById(id)));
    }
    
    async update(id: number, updateDto) {
        return ResultData.ok(await this.Repository.update(id, updateDto), "更新成功");
    }
    
    async removeByIds({ ids }) {
        return ResultData.ok(await this.Repository.delete({ id: In(ids) }), "删除成功");
    }
    
    async remove(id: number) {
        return ResultData.ok(await this.Repository.delete(id), "删除成功");
    }
}
